import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Enumeration;
import java.util.Vector;

public class TransactionWorker extends UnicastRemoteObject implements Worker {
	Resource db, noss;
	Task t;
	
	
	public TransactionWorker(Resource db, Resource noss) throws Exception {
		this.db = db;
		this.noss = noss;
	}
	
	public AccountRepresentation request(Task t) throws RemoteException {
		System.out.println("RMI Request Recieved...");
		Vector<Activity> activities = null;
		Vector results = new Vector();
		Enumeration itr;
		Activity activity;
		AccountRepresentation representation = new AccountRepresentation();
		ActivityResult result;
		boolean fail = false;
		
		activities = TaskSplitter.split(t);
		
		itr = activities.elements();
		while(itr.hasMoreElements() & (!fail)) {
			activity = (Activity) itr.nextElement();
			result = activity.execute(db, noss);
			results.add(result);
			if (result.getResult() <0 )
				fail = true;
		}
		
		representation.setSuccessful(true); //assume all is well
		
		itr = results.elements();
		while(itr.hasMoreElements()) {
			result = (ActivityResult) itr.nextElement();
			if (result.getResult() < 0) { //fail
				representation.setSuccessful(false);
				representation.addErrorMessage(result.getErrorMessages());
			}
			else { //succeed
				representation.addUpdates(result.getProperties());
			}
		}
		
		System.out.println("RMI Request Finished Processing...");
		return representation;
	}
}
